var thisPage = {
    first: 0,
    _rows: 0,
    // 初始化页面
    OnPageLoad: function () {
        // 判断审核状态，设置按钮的显示
        if (parent.$("#CheckedByName").val() !== "" || (parseInt(parent.$("#UserId").val()) !== parseInt(parent.$("#UpdatedBy").val()))) {
            $("#ButNew").hide();
            $("#ButSave").hide();
        } else {
            $("#ButNew").show();
            $("#ButSave").show();
        }
        thisPage.PageInit();
    },
    PageInit: function () {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/purchase/po/lines/surcharges/fetchAll.html",
            timeout: 30 * 1000,
            data: JSON.stringify(parent.$("#HeaderId").val()),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            thisPage.BuildDataTable(data);
        }).fail(function (data) {
            ajaxError(data, 1);
            $('#loading').hide();
        }).always(function ( ) {
            if (parseInt(thisPage.first) === 0) {
                thisPage.first = 1;
            }
        });
    },
    // 构建数据列表
    BuildDataTable: function (result) {
        $("#tabData01 tbody").empty();
        if (result === null) {
            $('#loading').hide();
            return false;
        }
        let content_01 = '';
        for (let i = 0; i < result.length; i++) {
            let id = result[i].linesId;
            let sequence = i + 1;
            content_01 += '<tr _mash_id="' + id + '">';
            content_01 += '<td style="text-align:center;">' + sequence + '</td>';
            if (parent.$("#ActionAcl_4").length === 0 || parseInt(parent.$("#ActionAcl_4").val() === 0)) {  // 无删除权限
                content_01 += '<td></td>';
            } else {
                // 判断审核状态，设置按钮的显示
                if (parent.$("#CheckedByName").val() !== "" || (parseInt(parent.$("#UserId").val()) !== parseInt(parent.$("#PurchasedBy").val()))) {
                    content_01 += '<td></td>';
                } else {
                    content_01 += '<td class="column__action"><span title="删除" class="trash" onclick="thisPage.DoDelete($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
                }
            }
            content_01 += '<td class="edited-cell">' + result[i].surcharges + '</td>';
            content_01 += '<td class="edited-cell">' + result[i].description + '</td>';
            content_01 += '</tr>';
            $("#tabData01 tbody").append(content_01);
            content_01 = '';
        }
        thisPage._rows = result.length;
        setOneTableRowColor("tabData01");
        SetSlaveTableHeight();

        let id = "cell__field";
        let name = "_cell__field";
        $('#tabData01 tbody tr').find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });

        $('#loading').hide();
    },
    // 得到明细
    GetLinesData: function () {
        let _arrInsert = [];
        let _arrUpdate = [];
        let _result = {};

        //得到修改过数据
        $('#tabData01 tbody').find("tr").each(function () {
            let _surcharges = $.trim($(this).find('td').eq(2).text());   // 附加费
            let _description = $.trim($(this).find('td').eq(3).text());  // 说明
            if ($(this).find("td.dirty").length) {
                let item = {};
                let $row = $(this);
                item['headerId'] = parent.$("#HeaderId").val();
                item['linesId'] = $row.attr("_mash_id");
                item['poNo'] = parent.$("#PoNo").val();
                item['surcharges'] = _surcharges;
                item['description'] = formatNullInputValue($.trim(_description));
                item['createdBy'] = parent.$("#UserId").val();
                item['updatedBy'] = parent.$("#UserId").val();

                if (parseInt($row.attr("_mash_id")) === 0) {
                    _arrInsert.push(item);
                } else {
                    _arrUpdate.push(item);
                }
            }
        });

        _result['HeaderId'] = parseInt(parent.$("#HeaderId").val());
        _result['Limit'] = parseInt(parent.$("#page-size_04").val());
        _result['PageIndex'] = parseInt(parent.$("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page"));
        _result['InsertList'] = _arrInsert;
        _result['UpdateList'] = _arrUpdate;

        return JSON.stringify(_result);
    },
    // 保存
    DoSave: function () {
        //step 1、进行页面验证，失败则返回
        var success_01 = CheckGridInput();
        if (!success_01)
            return;

        //step 2、执行处理
        $.ajax({
            type: "POST",
            url: parent.basePath + "/purchase/po/lines/surcharges/save.html",
            timeout: 30 * 1000,
            data: thisPage.GetLinesData(),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done(function (data) {
            // 刷新订单明细
            parent._InstancePageLines.BuildDataTable(data.PoLinesList);
            // 刷新附加费
            thisPage.BuildDataTable(data.SurchargesLinesList);
            ShowSuccessMessagePanel('保存成功。');
        }).fail(function (data) {
            ajaxError(data, 1);
        }).always(function ( ) {
        });
    },
    // 删除
    DoDelete: function ($self) {
        parent.showModal(350, 140, '确认删除', '', null, null, 1, '请问，确定要删除当前记录吗？',
                function () {
                    var instance = {};
                    instance['HeaderId'] = parseInt(parent.$("#HeaderId").val());
                    instance['LinesId'] = $self.parent().parent().attr("_mash_id");
                    instance['DeletedBy'] = parseInt(parent.$("#UserId").val());
                    instance['PoNo'] = parent.$("#PoNo").val();
                    instance['Desctiption'] = formatNullInputValue($.trim($self.parent().parent().find("td").eq(3).text()));
                    instance['Limit'] = parseInt(parent.$("#page-size_04").val());
                    instance['PageIndex'] = parseInt(parent.$("abbr.page_indicator_block,#wrapper__navbar_04").attr("_msh_page"));

                    $.ajax({
                        type: "POST",
                        url: parent.basePath + "/purchase/po/lines/surcharges/delete.html",
                        timeout: 30 * 1000,
                        data: JSON.stringify(instance),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        beforeSend: function () {
                        }
                    }).done(function (data) {
                        // 刷新订单明细
                        parent._InstancePageLines.BuildDataTable(data.PoLinesList);
                        // 刷新附加费
                        thisPage.BuildDataTable(data.SurchargesLinesList);
                        ShowSuccessMessagePanel('删除成功。');
                    }).fail(function (data) {
                        ajaxError(data, 1);
                    }).always(function ( ) {
                    });
                });
    },
    // 添加新行以及新行的操作方式
    DoInsert: function () {
        let $newLine = $('<tr class="newLine" _mash_id="0">' +
                '    <td style="height:24px;"></td>' +
                '    <td class="column__action"><span title="删除" class="trash" onclick="thisPage.RemoveNewLine($(this))"><i class="fa-all fa-trash-o fa-1"></i></span></td>' +
                '    <td class="edited-cell"></td>' +
                '    <td class="edited-cell"></td>' +
                '</tr>');
        $('#tabData01 tbody').prepend($newLine);   // 加在前面
        setOneTableRowColor("tabData01");
        thisPage._rows = thisPage._rows + 1;
        SetSlaveTableHeight();  // 自适应高度设置

        let id = "cell__field";
        let name = "_cell__field";
        $newLine.find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });
        return $newLine;
    },
    RemoveNewLine: function ($self) {
        $currRow = $self.parent().parent();
        parent.showModal(350, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？',
                function () {
                    $self.parent().parent().remove();
                    thisPage._rows = thisPage._rows - 1;
                    // 自适应高度设置
                    SetSlaveTableHeight();
                });
    }
};

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    thisPage.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    SetSlaveTableHeight();
}

// 根据窗口大小设置明细列表的高度（自适应高度）
function SetSlaveTableHeight() {
    let h = $(window).height();
    let _rc = Math.floor((h - $("#divD1").offset().top) / 25);
    let _dh = _rc * 25;
    let _tah = thisPage._rows * 25;
    _dh = (_tah >= _dh) ? _dh : _tah;

    $("#divD1").css({"max-height": _dh, height: _dh});
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
function CheckGridInput() {
    $('#tabData01 tbody').find("tr").each(function () {
        let $row = $(this);
        let _surcharges = $.trim($(this).find('td').eq(2).text());   // 附加费

        if (_surcharges !== '') {
            if (!isNumber(_surcharges)) {
                GridCheckErrHandle($row, 2, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($row, 2);
            }
        } else {
            GridCheckErrHandle($row, 2, '金额不能空。');
        }

    });
    if ($('#tabData01 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}